﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProgrammingSchool.DataContext;
using ProgrammingSchool.Repository.Interfaces;
using ProgrammingSchool.Repository.Repositories;
using ProgrammingSchool.Core.Interfaces;
using Messaging.Services;
using ProgrammingSchool.Core.Models;

namespace ProgrammingSchool.Core.Services
{
    public class UserService : IUserService
    {
        private readonly IUsersRepository _usersRepository;
        private readonly IEmailService _emailService;

        public UserService(IUsersRepository usersRepository, IEmailService emailService)
        {
            _usersRepository = usersRepository;
            _emailService = new EmailService();
        }

        public ServiceResult CreateNewUser(T_User user)
        {
            if (IsUserExist(user.Login))
                return new ServiceResult(StateEnum.Error, "User already exists.");

            try
            {
                _usersRepository.Save(user);
            }
            catch (Exception ex)
            {
                return new ServiceResult(StateEnum.Error, "Can't create new user.");
            }
            try
            {
                _emailService.Send("Registration success",
                                 "Registration on Programming School site",
                                 user.Login);
            }
            catch (Exception ex)
            {
                return new ServiceResult(StateEnum.Error, "Can't send mail." );
            }
            return new ServiceResult();
        }

        public void UpdatePassword(string login, string newPassword)
        {
            var user = _usersRepository.GetAll().Where(u => u.Login == login).FirstOrDefault();
            user.Password = newPassword;
            _usersRepository.Save(user);
        }

        public void DeleteUser(string login)
        {
            var user = _usersRepository.GetAll().Where(u => u.Login == login).FirstOrDefault();
            _usersRepository.Delete(user);
        }

        public T_User GetUser(string login, string password)
        {
            return _usersRepository.GetAll().Where(u => u.Login == login && u.Password == password).FirstOrDefault();
        }

        private bool IsUserExist(string login)
        {
            return _usersRepository.GetAll().Where(u => u.Login == login).Count() > 0;
        }
    }
}
